package com.feihong.yw189.activity.WebInterface;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.AppUtils;
import com.feihong.yw189.activity.yonghuzhongxin.wodexiaoxi.SystemNoticeDetailActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.http.Host;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.utils.ComPareUtils;
import com.feihong.yw189.utils.MyLoginUtils;
import com.feihong.yw189.utils.ToolsUtil;
import com.feihong.yw189.utils.UserLoginInfo;
import com.feihong.yw189.view.MyScrollviewWebview;
import com.just.agentweb.JsAccessEntrace;

import org.xutils.common.Callback;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class AjaxWebInterface {

    private static final String TAG = "页面AJAX";
    public static final String AJAX_KEY = "AndroidHttp";
    protected JsAccessEntrace agentWeb;
    private MyScrollviewWebview webView;
    private Context context;
    private SystemNoticeDetailActivity.IAjaxInterface mAjaxInterface;
    public AjaxWebInterface(MyScrollviewWebview webView) {
        this.webView = webView;
    }

    public AjaxWebInterface(Context context, JsAccessEntrace agentWeb) {
        this.agentWeb = agentWeb;
        this.context = context;
    }

    public AjaxWebInterface(Context context, JsAccessEntrace agentWeb, SystemNoticeDetailActivity.IAjaxInterface iAjaxInterface){
        this.agentWeb = agentWeb;
        this.context = context;
        mAjaxInterface = iAjaxInterface;
    }
    @JavascriptInterface
    public void jump(String str){
        if(mAjaxInterface == null){return;}
        HashMap<String,String> mParams = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(str);
        String url = jsonObject.getString("url");
        JSONObject data = jsonObject.getJSONObject("data");
        if(data != null){
            Set<Map.Entry<String, Object>> datas = data.entrySet();
            if(datas.size() > 0){
                Iterator<Map.Entry<String, Object>> iterator = datas.iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, Object> object = iterator.next();
                    mParams.put(object.getKey(), object.getValue() == null ? "" : object.getValue().toString());
                }
            }
        }
        String requestParams = new ComPareUtils.ComPareBuilder().putMap(mParams).create().getSignString();
        StringBuilder stringBuilder = new StringBuilder();
        Set<String> keySet = mParams.keySet();
        if(keySet.size() > 0){
            for(String key : keySet){
                stringBuilder.append("&" + key + "=" + mParams.get(key));
            }
        }
        url = Host.HTTP_HOME + url + "?sign=" +requestParams + stringBuilder.toString()+"&token=" + UserLoginInfo.getUserLoginInfoInstance().getUserToken();
        mAjaxInterface.jume(url);
    }
    @JavascriptInterface
    public int ajax(String postData) {
        try {
            JSONObject jsonObject = JSON.parseObject(postData);
            if (jsonObject == null || TextUtils.isEmpty(jsonObject.getString("url"))) {
                if (agentWeb != null) {
                    agentWeb.quickCallJs("ajaxError('参数不正确！')");
                }
                if (webView != null) {
                    webView.loadUrl("javascript:ajaxError('参数不正确！')");
                }
                return 0;
            }
            String url = jsonObject.getString("url");
            String success = jsonObject.getString("success");
            String error = jsonObject.getString("error");
            String timeOut = jsonObject.getString("timeout");
            HashMap<String, String> params = new HashMap<>();
            if (jsonObject.containsKey("data")) {
                Set<Map.Entry<String, Object>> datas = jsonObject.getJSONObject("data").entrySet();
                if (datas != null && datas.size() > 0) {
                    Iterator<Map.Entry<String, Object>> iterator = datas.iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, Object> object = iterator.next();
                        params.put(object.getKey(), object.getValue() == null ? "" : object.getValue().toString());
                    }
                }
            }
            params.put("token", UserLoginInfo.getUserLoginInfoInstance().getUserToken());
            params.put("time", "" + MyLoginUtils.getCuurrentTime());
            params.put("version",  "and." + AppUtils.getAppVersionName());
            String sign = ToolsUtil.getsignRes("", params);
            params.put("sign", sign);
            new Thread(new POSTThread( url, success, params,error,timeOut)).start();
        } catch (Exception ex) {
            if (agentWeb != null) {
                agentWeb.callJs("ajaxError('数据解析错误')");
            }
            if (webView != null) {
                webView.loadUrl("javascript:ajaxError('数据解析错误！')");
            }
            return 0;
        }
        return 1;
    }

    /**
     * 联系客服
     * @param info
     */
    @JavascriptInterface
    public void get_service(String info){
        mAjaxInterface.toService(info);
    }
    public class POSTThread implements Runnable {

        private String url;
        private String success;
        private HashMap<String, String> params;
        private String error;
        private int timeOut;
        public
        POSTThread( String url, String success, HashMap<String, String> params,String error,String timeOut) {

            this.url = url;
            this.params = params;
            this.success = success;
            this.error = error;
            if(!TextUtils.isEmpty(timeOut)){
                this.timeOut = Integer.valueOf(timeOut);
            }
        }

        @Override
        public void run() {
            try {
                App.getApp().getHttpTools().ajaxPost(this.url, this.params, this.timeOut, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if (agentWeb != null) {
                            agentWeb.callJs(success + "('" + result + "')");
                        }
                        if (webView != null) {
                            webView.loadUrl("javascript:" + success + "('" + result + "')");
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        if (agentWeb != null) {
                            agentWeb.callJs(error + "()");
                        }
                        if (webView != null) {
                            webView.loadUrl("javascript:"+error+"()");
                        }
                    }

                    @Override
                    public void onCancelled(Callback.CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {
                        params = null;
                    }
                });
            } catch (Exception ex) {
                if (agentWeb != null) {
                    agentWeb.callJs("ajaxError('请求失败')");
                }
                if (webView != null) {
                    webView.loadUrl("javascript:ajaxError('请求失败，程序出错！')");
                }
            }
        }
    }

}
